package org.ziegler.netty.cp8;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.util.AttributeKey;

import java.net.InetSocketAddress;

public class TestClient {

    public static void main(String[] args) throws InterruptedException {
        TestClient testClient = new TestClient();
        testClient.connect("127.0.0.1", 8080);
    }

    void connect(String remoteIP, int port) throws InterruptedException {

        final AttributeKey<Integer> id = AttributeKey.newInstance("ID");

        EventLoopGroup group = new NioEventLoopGroup();
        Bootstrap b = new Bootstrap();
        b.group(group)
                .channel(NioSocketChannel.class)
                .remoteAddress(new InetSocketAddress(remoteIP, port))
                .handler(new ChannelInitializer<SocketChannel>() {

                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline().addLast(new SimpleChannelInboundHandler<ByteBuf>() {

                            @Override
                            public void channelActive(ChannelHandlerContext ctx) throws Exception {
                                System.out.println("ctx.channel().attr(id) = " + ctx.channel().attr(id));

                            }

                            @Override
                            protected void channelRead0(ChannelHandlerContext ctx, ByteBuf msg) throws Exception {

                            }
                        });
                    }
                });

        b.attr(id, 123456);

        ChannelFuture f = b.connect().sync();
        f.addListener(future -> {
            if (f.isSuccess()) {
                System.out.println("connect to " + remoteIP + ":" + port + " success");
            } else {
                System.out.println("connect failed.");
            }
        });

    }
}
